﻿using SuperX.Common.BasicService;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace SuperX.Common.Scheduler
{
    // 
    public class SchedulerGroup
    {
        // 
        public SchedulerGroup(List<IScheduler> dispatchers, bool isSort)
        {
            this._dispatchers = dispatchers;
            this._isSort = isSort;
        }

        // 
        public void Start()
        {
            Timer timer = this._timer;
            if (timer != null)
            {
                timer.Change(-1, -1);
            }
            Timer timer2 = this._timer;
            if (timer2 != null)
            {
                timer2.Dispose();
            }
            this._timer = new Timer(new TimerCallback(this.OnTrick), this, 0, this._unitTime);
        }

        // 
        private void OnTrick(object state)
        {
            try
            {
                if (!this._isInvoke && BasicServiceManager.GetProjService().Project.Status == ControllerStatus.Running)
                {
                    this._isInvoke = true;
                    List<SchedulerMsg> list = new List<SchedulerMsg>();
                    foreach (IScheduler dispatcher in this._dispatchers)
                    {
                        SchedulerValue dispatchValue;
                        if (dispatcher.Check(out dispatchValue))
                        {
                            list.Add(new SchedulerMsg(dispatcher, dispatchValue));
                        }
                    }
                    if (list.Count > 0)
                    {
                        if (this._isSort)
                        {
                            list.Sort();
                        }
                        DateTime now = DateTime.Now;
                        foreach (SchedulerMsg dispatcherMsg in list)
                        {
                            dispatcherMsg.Dispatcher.Invoke(dispatcherMsg.DispatchValue);
                        }
                        double totalMilliseconds = (DateTime.Now - now).TotalMilliseconds;
                    }
                    this._isInvoke = false;
                }
            }
            catch
            {
                this._isInvoke = false;
            }
        }

        // 
        public void Stop()
        {
            Timer timer = this._timer;
            if (timer != null)
            {
                timer.Dispose();
            }
            foreach (IScheduler dispatcher in this._dispatchers)
            {
                dispatcher.Stop();
            }
        }

        // 
        private List<IScheduler> _dispatchers;

        //
        private Timer _timer;

        // 
        private int _unitTime = 50;

        // 
        private bool _isInvoke;

        // 
        private bool _isSort;
    }
}
